<template>
  <div
    class="apps-forms apps-menu-container"
    v-jloading="loading"
  >
    <div class="apps-menu-actions">
      <div
        class="apps-menu-actionitem"
        :class="{ 'active': typeTab === 'all' }"
        @click="handleChangeTab('all')"
      >全部</div>
      <div
        class="apps-menu-actionitem"
        :class="{ 'active': typeTab === 'form' }"
        @click="handleChangeTab('form')"
      >普通类</div>
      <div
        class="apps-menu-actionitem"
        :class="{ 'active': typeTab === 'flow' }"
        @click="handleChangeTab('flow')"
      >流程类</div>
      <div class="apps-menu-actionitem none">
        <el-dropdown
          trigger="click"
          placement="bottom-start"
          @command="handleShowCreate"
        >
          <JIcon :icon="DFT_ICONS.add" class="app-portal-action" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="form">
                <JIcon :icon="DFT_ICONS.add" />普通表单
              </el-dropdown-item>
              <el-dropdown-item command="user" v-if="!isExistAppAdmin">
                <JIcon :icon="DFT_ICONS.add" />应用用户表单
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <el-input v-model="queryText" class="thin-search-input" clearable placeholder="按名称搜索"></el-input>
    <el-scrollbar
      class="app-form-items"
      :settings="{}">
      <draggable v-model="forms" @end="handleDragEndEvent">
        <template #item="{ element: f, index }" :key="f">
          <span
            class="menu-custom-tree-node menu-icon-node menu-icon-container"
            :style="$menuUtils.getIconStyleVar(f)"
            :class="{ 'active': form && form.form_id === f.form_id }"
            @click="handleClick(f)">
            <span
              class="menu-custom-icon menu-icon"
              :style="$menuUtils.getFormIconStyle(f)"
            >
              <JIcon
                :icon="$menuUtils.getFormIcon(f)"
              />
            </span>
            <div class="menu-custom-name">
              <div v-text="f.form_name"></div>
              <span v-text="f.form_code"></span>
            </div>
            <JIcon
              v-if="f.use_type === 'WORKFLOW'"
              :icon="DFT_ICONS.formflow"
              class="app-icon"
              v-tippy="{ arrow: true }"
              content="流程类表单"
            />
          </span>
        </template>
      </draggable>
    </el-scrollbar>
<!--    <el-dialog
      :title="winName"
      v-model="showCreate"
      :fullscreen="true" custom-class="m-dialog-fullscreen"
      :close-on-click-modal="false" :append-to-body="true">
      <form-create
        v-if="showCreate" @close="handleCloseFormWin"
        :formInfo.sync="formInfo"
        :show.sync="showCreate"
        :use-type="useType"></form-create>
    </el-dialog>-->
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import _ from 'lodash';
import { ElMessage } from 'element-plus';
import { $menuUtils } from "@jzl/utils";
import {api} from "@jzl/api";
import draggable from 'vuedraggable';
import {DFT_ICONS} from "@jzl/icons";
import {$WinFormCreate} from "@jzl/comps-mg/src/form/src/win-form-setting.js";

const props = defineProps({
  appId: {
    type: Number,
    required: true
  },
  selectedId: {
    type: [Number, String],
    default: null
  }
});

const emit = defineEmits(['select']);

const queryText = ref("");
const loading = ref(false);
const form = ref(null);

const formsAll = ref([]);
const forms = ref([]);
const typeTab = ref('all');

const showCreate = ref(false);
const formInfo = ref(null);
const useType = ref('WEB');
const winName = ref('新增表单');

const isExistAppAdmin = computed(() => {
  let idx = _.findIndex(formsAll.value, it => {
    return _.startsWith(it.form_code, "_admin_");
  });

  return idx >= 0;
});

const refresh = () => {
  init();
};

const init = async () => {
  let formsData, count;

  loading.value = true;

  if (props.appId) {
    let data = await api.form.getFormList(_.assign({
      app_id: props.appId,
      page: 1,
      pageSize: 10000
    }, {}));

    formsData = _.get(data, 'rows', []);
    count = _.get(data, 'count', 0);
  }

  formsAll.value = formsData;
  forms.value = formsData;
  loading.value = false;

  filterDatas();
  selectDefaultForm();
};

const selectDefaultForm = () => {
  if (form.value) return;

  let dftId = props.selectedId;
  if (!dftId) dftId = _.get(formsAll.value, `[0].form_id`);
  if (!dftId) return;

  let formItem = _.find(formsAll.value, f => f.form_id == dftId);
  if (formItem) {
    handleClick(formItem);
  }
};

const handleChangeTab = (tab) => {
  typeTab.value = tab;
};

const handleClick = (data) => {
  form.value = data;
  emit('select', data);
};

const filterDatas = () => {
  let filteredForms = [];
  if (typeTab.value === 'form') {
    filteredForms = _.filter(formsAll.value, f => {
      return f.use_type !== 'WORKFLOW';
    });
  } else if (typeTab.value === 'flow') {
    filteredForms = _.filter(formsAll.value, { use_type: 'WORKFLOW' });
  } else {
    filteredForms = formsAll.value;
  }

  if (_.trim(queryText.value)) {
    let reg = new RegExp(queryText.value);
    filteredForms = _.filter(filteredForms, (f) => {
      return reg.test(f.form_name);
    });
  }

  forms.value = filteredForms;
};

const handleShowCreate = (cmd) => {
  let info = { app_id: props.appId };
  let useTypeValue = "WEB";

  if (cmd === 'form') {
    useTypeValue = "WEB";
  } else if (cmd === 'flow') {
    useTypeValue = "WORKFLOW";
  } else if (cmd === 'user') {
    info.is_user = 1;

    if (isExistAppAdmin.value) {
      ElMessage.warning("应用下已有应用用户表单，请前去修改！");
      return;
    }
  }

  // useType.value = useTypeValue;
  // formInfo.value = info;
  // showCreate.value = true;
  // winName.value = '创建表单';

  $WinFormCreate({
    useType: useTypeValue,
    formInfo: info,
    isShowForm: true,
    onCancel: () => {
      handleCloseFormWin();
    }
  }, {
    title: '创建表单',
  });
};

const handleCloseFormWin = (isRefresh) => {
  if (isRefresh) {
    init();
  }

  showCreate.value = false;
};

const handleDragEndEvent = async () => {
  let ids = [];
  _.each(forms.value, (it, idx) => {
    it.order = idx + 1;
    ids.push(it.form_id);
  });

  await api.form.move(ids);
  init();
};

onMounted(() => {
  init();
});

watch(() => props.appId, () => {
  init();
});

watch(() => typeTab.value, () => {
  filterDatas();
});

watch(() => queryText.value, () => {
  filterDatas();
});

watch(() => props.selectedId, () => {
  selectDefaultForm();
});
</script>
